package com.indusfo.spc.service.impl;


import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.interceptor.UserThreadLocal;
import com.indusfo.spc.mapper.DepMapper;
import com.indusfo.spc.mapper.UserMapper;
import com.indusfo.spc.pojo.Dep;
import com.indusfo.spc.pojo.User;
import com.indusfo.spc.service.DepService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XCommonUtil;
import com.indusfo.spc.vo.XTreeNode;
import com.indusfo.spc.vo.XTreeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class DepServiceImpl implements DepService {
    private  static  final Logger logger = LoggerFactory.getLogger(DepServiceImpl.class);

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Resource
    private DepMapper depMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 新增修改
     *
     * @param dept
     * @return
     */
    @Override
    public JSONObject creatDepts(Dep dept) {
        String successMsg = "";
        // 创建人id从本地线程类获得
        User user = UserThreadLocal.get();
        dept.setUserId(user.getUserId());
        if(dept.getDepPid()==null){
            dept.setDepPid(0);
        }
        try{
            // 参数校验
            checkParam(dept);
            //新增
            if (dept.getDepId() == null || "".equals(dept.getDepId())) {
                Integer over = depMapper.insertDepts(dept);
                if (over < 1) {
                    return JSONObject.build(505, "新增失败");
                }
                successMsg = "新增成功";
                return JSONObject.build(200, successMsg ,dept.getDepId());
            } else {
                //修改
                if(dept.getDepPid()==null){
                    dept.setDepPid(0);
                }
                //判断部门编码是否更改
                int num = depMapper.judgeDepCode(dept);
                if(num == 0) {
                    throw new ParamsErrorException("部门编码不允许更改");
                }
                Integer over = depMapper.updateDepts(dept);
                if (over < 1) {
                    return JSONObject.build(505, "修改失败");
                }
                successMsg = "修改成功";
                return JSONObject.build(200, successMsg);
            }
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }

    }

    /**
     * 删除
     *
     * @param dept
     * @return
     */
    @Transactional
    @Override
    public JSONObject deleteDepts(Dep dept) {
        String msg = "";
        try {
            if (dept.getDepId() == null) {
                throw new ParamsErrorException("部门id不能为空");
            }
            //查询是否有子集
            Integer count = depMapper.lookDeptsBylDepPar(dept);
            if(count>0){
                    throw new ParamsErrorException("该部门下还有子集");
            }
//          else {
//            结连删除用户
//              msg = "删除成功";

//              Integer depId = dept.getDepId();
//              int flag = userMapper.deleteUserBylDeptId(depId);
//              if(flag==0){
//                  new ModifyFailedException("删除失败");

//              }
//          }
            //查询部门下是否有用户
            User user = new User();
            user.setDepId(dept.getDepId());
            List<User> users = userMapper.listUserDep(user);
            if(users.size()>0){
                throw new ParamsErrorException("该部门下还有用户");
            }
            // 执行删除
            int row = depMapper.deleteDepts(dept);
            if (row == 0) {
                new ModifyFailedException("删除失败");
            }
            msg="删除成功";
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
        return JSONObject.build(200, msg);
    }


    /**
     * 查看部门  集合
     *
     * @param dept
     * @return
     */
    @Override
    public JSONObject lookDepts(Dep dept) {
        List<Dep> listDepts = new ArrayList<>();
        Integer num = null;
        try {

            Integer pagesize = dept.getPagesize();
            Integer pageindex = dept.getPageindex();
            if (pagesize != null && pageindex != null) {
                dept.setIncept(pagesize * (pageindex - 1));
            }
            listDepts = depMapper.lookDepts(dept);
            num = depMapper.tallys(dept);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return JSONObject.oK("查询成功", listDepts, num);
    }

    /**
     * 查看部门   树
     *
     * @param dept
     * @return
     */
    @Override
    public JSONObject detpsTree(Dep dept) {
        List<XTreeNode> tree = null;
        try {
            tree = new ArrayList<>();
            List<XTreeNode> nodes = new ArrayList<>();
            List<Dep> list = depMapper.lookDepts(dept);
            if(dept.getFlag()!=null){
                // 树中加入全部
                Dep dep = new Dep();
                dep.setDepId(0);
                dep.setDepPid(0);
                dep.setDepCode("全部");
                dep.setDepName("全部");
                list.add(0,dep);
                //生成树list
                if (null != list) {
                    List<XTreeNode> treelist = new ArrayList<>();
                    for (Dep _MouldType : list) {
                        XTreeNode node = new XTreeNode();
                        node.setId(_MouldType.getDepId());
                        node.setpId(_MouldType.getDepPid());
                        node.setTitle(_MouldType.getDepName());
                        node.setCode(_MouldType.getDepCode());
                        treelist.add(node);
                    }
                    XTreeUtil xTreeUtil = new XTreeUtil(dept.getFlag(), treelist);
                    List<Integer> childs = new ArrayList<>();
                    List<Integer> parents = new ArrayList<>();
                    childs = xTreeUtil.getChilds();
                    parents = xTreeUtil.getParents();
                    if (null != list) {
                        for (Dep _MouldType : list) {
                            XTreeNode node = new XTreeNode();
                            node.setId(_MouldType.getDepId());
                            node.setpId(_MouldType.getDepPid() == 0 ? null : _MouldType.getDepPid());
                            if (parents.contains(_MouldType.getDepId())) {
                                node.setExpand(true);
                            }
                            if (!dept.getFlag().equals(0)) {
                                if (dept.getFlag().equals(_MouldType.getDepId())) {
                                    node.setSelected(true);
                                }
                            }
                            node.setTitle(_MouldType.getDepName());
                            node.setCode(_MouldType.getDepCode());
                            nodes.add(node);
                        }
                    }
                }
                tree = XCommonUtil.getTree(nodes, null);
                if(dept.getFlag().equals(0)){
                    tree.get(1).setSelected(true);
                }
            }else {
                if (null != list) {
                    for (Dep _MouldType : list) {
                        XTreeNode node = new XTreeNode();
                        node.setId(_MouldType.getDepId());
                        node.setpId(_MouldType.getDepPid() == 0 ? null : _MouldType.getDepPid());
                        node.setTitle(_MouldType.getDepName());
                        node.setCode(_MouldType.getDepCode());
                        nodes.add(node);
                    }
                }
                tree = XCommonUtil.getTree(nodes, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.oK(tree);
    }


    /**
     * 参数校验
     *
     * @param dept
     *
     */
    private void checkParam(Dep dept) {
        if(("").equals(dept.getDepCode())) {
            throw new ParamsErrorException("部门编码不能为空");
        }
        if(dept.getDepCode().getBytes().length>50) {
            throw new ParamsErrorException("部门编码长度过长,限制50");
        }
        if(("").equals(dept.getDepName())) {
            throw new ParamsErrorException("部门名称不能为空");
        }
        if(dept.getDepName().getBytes().length>50) {
            throw new ParamsErrorException("部门名称长度过长,限制50");
        }
        //编码重复与否
        Integer repeat = depMapper.repeat(dept.getDepId(), dept.getDepCode());
        if (repeat > 0) {
            throw new ParamsErrorException("编码不能重复");
        }
        //名称重复与否
        Integer repeat1 = depMapper.repeatName(dept.getDepId(), dept.getDepName());
        if (repeat1 > 0) {
            throw new ParamsErrorException("名称不能重复");
        }
    }
}
